﻿using System;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Ha666.Common;
using Ha666.Redis;
using Ha666.WebAPI.Models.Request;

namespace Ha666.WebAPI.Controllers
{
    public class SystemController : ApiController
    {

        private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        [HttpPost]
        public HttpResponseMessage GetTime(GetTimeRequest request)
        {
            HttpResponseMessage response = null;
            try
            {
                string HostName = "";
                var headers = HttpContext.Current.Request.Headers;
                if (headers["HostName"] != null)
                    HostName = headers["HostName"];
                string tokenResult = VerifiedParams.VerfiedToken(request.Token);
                if (tokenResult != "")
                {
                    Logger.Error(string.Format("【GetTime】Token异常，HostName={0},tokenResult={1}", HostName, tokenResult));
                    response = Request.CreateResponse(HttpStatusCode.Forbidden, "");
                    response.ReasonPhrase = HttpUtility.UrlEncode(string.Format("【System.GetTime】HostName={0},Error:{1}", HostName, tokenResult));
                    return response;
                }
                var key = new StringKey("ha666");
                var list = key.Time(0);
                if (list == null)
                {
                    return Request.CreateResponse(HttpStatusCode.Forbidden, "查询出错");
                }
                return Request.CreateResponse(HttpStatusCode.OK, new ServerTime { Time = Utility.GetTime(list[0]).ToString("yyyy-MM-dd HH:mm:ss") }, new ProtoBufFormatter());
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("【GetTime】异常：{0}", exception.Message));
                response = Request.CreateResponse(HttpStatusCode.Forbidden, "");
                response.ReasonPhrase = HttpUtility.UrlEncode("exception:" + exception.Message);
                return response;
            }
        }

    }
}
